<template>
  <view class="container">
    <custom-pageload v-if="isLoading"></custom-pageload>

    <template v-else>
      <!-- 导航 -->
      <custom-nav leftIcon="search" theme="primary"></custom-nav>

      <!-- 列表滚动区域 -->
      <view class="content">
        <scroll-view style="height: 100%" :scroll-y="true" :refresher-enabled="true" :refresher-isRefresh="isRefresh" refresher-background="transparent" :refresher-threshold="100"
          :scroll-with-animation="true" @refresherrefresh="onRefresh" @refresherrestore="onRestore" @scrolltolower="onLower" @scroll="onScroll" :refresher-triggered="isRefresh">
          <!-- 轮播 -->
          <custom-swiper :list="imgList" mode="dot"></custom-swiper>

          <!-- 顶部卡片 -->
          <template v-if="myInfo.appLogin">
            <menu-card :total="total" :mate_address="myInfo.mate_address" :look_my="look_my" @toRegion="toRegion" v-if="myInfo.phone"></menu-card>
            <tips-card btype="index" v-else></tips-card>
          </template>

          <top-card v-else></top-card>

          <template v-if="total">
            <!-- 资料卡片 -->
            <view style="padding-bottom: 1rpx">
              <person-card v-for="(item, index) in personList" :key="index" :info="item">
                <template #footer>
                  <view class="mask-lock" v-if="!myInfo.appLogin && index == personList.length - 1">
                    <more-card mtype="notlogin"></more-card>
                  </view>
                </template>
              </person-card>
            </view>
            <template v-if="myInfo.appLogin && myInfo.phone">
              <!-- 已登录 - 未完成三个择偶地区 -->
              <template v-if="personList.length == total && !myInfo.isFullAddress">
                <more-card mtype="region" @click="toRegion" v-if="personList.length == total"></more-card>
              </template>
              <!-- 加载更多 -->
              <custom-load :status="loadStatus" v-else></custom-load>
            </template>
          </template>

          <custom-empty @click="toRegion" v-else :emptyInfo="emptyInfo"></custom-empty>
        </scroll-view>
      </view>

      <!-- 底部卡片 -->
      <!-- 未登录状态 -->
      <bottom-card v-if="!myInfo.appLogin" btype="notlogin"></bottom-card>

      <!-- 已登录状态 - 未登记手机号 -->
      <template v-else>
        <bottom-card v-if="!myInfo.phone" btype="phone"></bottom-card>

        <view :style="isHideStyle" v-else-if="!myInfo.isComplete">
          <bottom-card btype="complete"></bottom-card>
        </view>
      </template>
    </template>

    <!-- 隐私政策 -->
    <custom-privacy v-if="isPrivacy"></custom-privacy>
  </view>
</template>

<script setup>
import PersonCard from "@/components/common/person-card.vue";
import MoreCard from "@/components/common/more-card.vue";
import TipsCard from "@/components/common/tips-card.vue";
import TopCard from "./components/top-card.vue";
import MenuCard from "./components/menu-card.vue";
import BottomCard from "./components/bottom-card.vue";

// 引入pina + api
import { getItem, setItem } from "@/utils/storage";
import { fetchIndexList } from "@/api/index";
import { fetchMessageList } from "@/api/message";
import { urlConf } from "@/config/resource";
import useStore from "@/store";
const { app, common } = useStore();

const imgList = reactive([
  {
    img: urlConf + "common/banner1.png",
  },
  {
    img: urlConf + "common/banner2.png",
    url: "/subPages/member/supreme",
  },
]);

const isPrivacy = ref(false);
const isRefresh = ref(false);
const isLoading = ref(true);
const myInfo = ref({});
const total = ref(0);
const loadStatus = ref("");
const look_my = ref(0);
const personList = ref([]);
const timer = ref(null);
const filterQuery = reactive({
  page: 1,
  limit: 20,
});
const isHideStyle = reactive({
  height: "140rpx",
  transition: "1s",
  overflow: "hidden",
});
// 首页无数据时
const emptyInfo = reactive({
  title: "当前地区暂无符合条件的对象",
  tips: "去添加择偶地区吧",
  btnText: "去添加",
});
// 去添加按钮
const toRegion = () => {
  const { appLogin, phone } = getItem("user_info") || {};
  if (!appLogin) {
    setTimeout(() => {
      uni.navigateTo({ url: "/subPages/register/index" });
    }, 100);
    return;
  }
  if (!phone) {
    setTimeout(() => {
      uni.navigateTo({ url: "/subPages/register/index" });
    }, 100);
    return;
  }
  const { mate_address, at_province: province, at_city: city } = myInfo.value;
  if (mate_address) {
    setItem("editUser", { mate_address: JSON.parse(mate_address) });
  } else {
    const default_address = [{ province, city }];
    setItem("editUser", { mate_address: default_address });
  }
  setTimeout(() => {
    uni.navigateTo({ url: "/subPages/complete/region" });
  }, 100);
};
const onRestore = () => {
  uni.showToast({
    title: "刷新成功~",
    icon: "none",
  });
};

// 监听滚动事件
const onScroll = (e) => {
  const top = e.detail.scrollTop;
  if (top >= 20) {
    isHideStyle.height = "0rpx";
  } else {
    isHideStyle.height = "140rpx";
  }
};

// 页面下拉刷新
const onRefresh = () => {
  isHideStyle.height = "140rpx";
  filterQuery.page = 1;
  isRefresh.value = true;
  getList(true);
};

// 向上滑动加载更多
const onLower = () => {
  if (!myInfo.value.appLogin) return;

  loadStatus.value = "loading";
  ++filterQuery.page;

  getList(false);
};

// 获取列表
const getList = async (refresh = true) => {
  const params = {
    page: filterQuery.page,
    limit: filterQuery.limit,
  };

  const { gender, at_city } = getItem("user_info") || {};
  if (gender) params.gender = gender;
  if (at_city) params.at_city = at_city;

  try {
    const { data } = await fetchIndexList(params);
    const { page, list } = data;
    isRefresh.value = false;
    isLoading.value = false;

    total.value = page?.total;
    list.forEach((v) => {
      v.year = String(v.year).slice(-2);
      v.imgs = v.img || [];
      // v.yesday 1: 昨天   2： 今天
    });

    personList.value = refresh ? list : personList.value.concat(list);
    if (personList.value.length >= total.value) {
      loadStatus.value = "nomore";
    }
  } catch (error) {
    isRefresh.value = false;
    isLoading.value = false;
  }
};

// 获取上一页路由 - 更新当前页数据
const refreshPage = () => {
  const lastPage = getItem("lastPage");
  uni.removeStorageSync("lastPage");
  if (lastPage) {
    // 特定页面返回首页 - 刷新列表
    const ks = ["register", "contact", "verify"];
    let isFresh = false;
    ks.forEach((v) => {
      if (lastPage.includes(v)) isFresh = true;
    });
    if (isFresh) {
      filterQuery.page = 1;
      getList();
      return;
    }
  }
  // 返回首页 - 更新收藏状态 + 更新解锁电话状态
  const { user_id, collect, look } = getItem("userIds") || {};
  if (user_id) {
    personList.value.forEach((v) => {
      if (v.id == user_id) {
        if (collect == 0 || collect == 1) {
          v.collect = collect;
        }
        if (look == 0 || look == 1) {
          v.look = look;
        }
      }
    });
  }
};

// 更新对应项解锁状态
const refreshFn = (id, look) => {
  personList.value.forEach((v) => {
    if (v.id == id) {
      v.look = look;
    }
  });
};

// 获取 谁看过我
const getLookMy = async () => {
  const { data } = await fetchMessageList({ page: 1, limit: 1 });
  look_my.value = data?.count?.look_my;
};

// 是否打开隐私弹窗
const privacyOpen = () => {
  const flag = getItem("privacy");
  if (flag) {
    isPrivacy.value = true;
    nextTick(() => {
      common.updatePrivacyOpen(true);
      uni.removeStorageSync("privacy");
    });
  }
};

watch(
  () => common.isPopupOpen,
  (v) => {
    if (v) {
      clearTimeout(timer.value);
    } else {
      openSkill();
    }
  }
);

// 未完善资料 - 打开脱单小技巧
const openSkill = () => {
  if (myInfo.value.appLogin && myInfo.value.phone) {
    if (!myInfo.value.isComplete) {
      const s = getItem("initSkillStatus");

      if (s == true || s == "true") {
        timer.value = setTimeout(() => {
          const len = getCurrentPages().length;
          const path = getCurrentPages()[len - 1].route;
          const fPage = path == "pages/index/index";
          if (fPage) {
            common.updatePopupOpen(true, "skill");
            setItem("initSkillStatus", false);
          }
        }, 20000);
      }
    }
  }
};

// 获取个人信息
const getInfo = async () => {
  privacyOpen();
  refreshPage();
  app
    .getUserInfo()
    .then((res) => {
      myInfo.value = res;

      if (!res.appLogin) return;
      if (!res.phone) return;

      openSkill();
      getLookMy();
    })
    .catch((err) => {
      myInfo.value = {};
    });
};

onShow(async () => {
  await getInfo();
});

onLoad(async () => {
  await getList();
  // 创建激励视频广告
  common.initAdCase("index");
});

provide("pageType", "index");
provide("refreshFn", refreshFn);
</script>

<style lang="scss" scoped>
.container {
  background: #f5f5f5;
  .content {
    background: transparent;
  }
}
</style>
